package org.example.filelisten;

import org.apache.commons.io.filefilter.FileFilterUtils;
import org.apache.commons.io.filefilter.HiddenFileFilter;
import org.apache.commons.io.filefilter.IOFileFilter;
import org.apache.commons.io.monitor.FileAlterationListenerAdaptor;
import org.apache.commons.io.monitor.FileAlterationMonitor;
import org.apache.commons.io.monitor.FileAlterationObserver;

import java.io.File;
import java.util.concurrent.TimeUnit;

public class FileListen extends FileAlterationListenerAdaptor {

    @Override
    public void onFileCreate(File file) {
        System.out.println(file.getName());
    }

    @Override
    public void onStart(FileAlterationObserver observer) {
//        System.out.println(observer.toString());
    }

    public static void main(String[] args) {
        String path = "/Users/yeym/Downloads";
        // 轮询间隔1秒
        long interval = TimeUnit.SECONDS.toMillis(1);
        System.out.println(interval);
        // 创建过滤器
        IOFileFilter directories = FileFilterUtils.and(
                FileFilterUtils.directoryFileFilter(),
                HiddenFileFilter.VISIBLE);
        IOFileFilter files    = FileFilterUtils.and(
                FileFilterUtils.fileFileFilter(),
                FileFilterUtils.suffixFileFilter(".jpg"));
        IOFileFilter filter = FileFilterUtils.or(directories, files);
        //不使用过滤器
        FileAlterationObserver observer = new FileAlterationObserver(new File(path),filter);
        observer.addListener(new FileListen());
        //创建文件变化监听器
        FileAlterationMonitor monitor = new FileAlterationMonitor(interval, observer);
        // 开始监控
        try {
            monitor.start();
            Thread.sleep(5000);
            monitor.stop();
        } catch (Exception e) {
            e.printStackTrace();
        }
    }
}
